/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2011 www.pretty-tools.com
 */

var wwwPrettyTools_GooglePlusOneButtonToollbar = {
    GOOGLE_PLUS_ONE_API_URL: "https://apis.google.com/js/plusone.js",
    GOOGLE_PLUS_ONE_FRAME_URL: "https://apis.google.com/u/0/_/+1/fastbutton?usegapi=1&bsv=o&size=standard&count=true&hl=en&url=%url%&origin=%origin%&parent=%parent%&gsrc=3p&ic=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.ru._EQg8N9EI7Q.O%2Fm%3D__features__%2Fam%3DIQ%2Frt%3Dj%2Fd%3D1%2Frs%3DAItRSTNEfOH1MlcNEtB3fzWuGFFYKeAB0g#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh",
    GOOGLE_PLUS_SHARE_URL: "https://plus.google.com/share?hl=en&url=%url%",
    GOOGLE_PLUS_ONE_DOMAIN: "apis.google.com",
    GOOGLE_PLUS_ONE_FRAME_TEST: "/fastbutton",
    DIV_ID: "GooglePlusOneButtonByPrettyToolsDiv",
    TOOLBAR_BUTTON_ID: "Google_Plus_One_Button_Pretty_Tools",
    SUCCESSFULLY_INSTALLED_URL: "http://googleplusone.pretty-tools.com/installed_for_firefox.php"
};

wwwPrettyTools_GooglePlusOneButtonToollbar.onLoad = function(event)
{
    try
    {
        window.addEventListener("pageshow", function(e) {
            wwwPrettyTools_GooglePlusOneButtonToollbar.onPageShow(e);
        }, false);

        gBrowser.mTabContainer.addEventListener("select", function(e) {
            wwwPrettyTools_GooglePlusOneButtonToollbar.updateToolbarButton();
        }, false);

        if (wwwPrettyTools_GooglePlusOneButtonConfiguration.isFirstStart()) {
            this.installButtonOnToolbar();
            // need to open page with instructions
            setTimeout(function() {
                // open page with instructions
                gBrowser.selectedTab = gBrowser.addTab(wwwPrettyTools_GooglePlusOneButtonToollbar.SUCCESSFULLY_INSTALLED_URL);
            }, 2000);
        }

        var locale = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).QueryInterface(Components.interfaces.nsIPrefBranch).getBranch("general.").getCharPref("useragent.locale");
        if (locale.length > 0)
        {
            //this.GOOGLE_PLUS_ONE_FRAME_URL = this.GOOGLE_PLUS_ONE_FRAME_URL.replace("&hl=en&", "&hl=" + locale + "&");
            this.GOOGLE_PLUS_SHARE_URL = this.GOOGLE_PLUS_SHARE_URL.replace("?hl=en&", "?hl=" + locale + "&");
        }
    }
    catch(ex)
    {
        dump("Exception during onLoad: " + ex + "\n");
    }
}

wwwPrettyTools_GooglePlusOneButtonToollbar.installButtonOnToolbar = function ()
{
    try
    {
        var btn = document.getElementById(this.TOOLBAR_BUTTON_ID);
        if (btn) // button exists
            return;

        // let's add it
        var navBar = document.getElementById("nav-bar");
        if (!navBar)
            return;

        var currentSet = navBar.getAttribute("currentset");
        if (!currentSet)
            currentSet = navBar.currentSet;

        var curSet = currentSet.split(",");
        if (curSet.indexOf(this.TOOLBAR_BUTTON_ID) == -1)
        {
            var set = curSet.concat(this.TOOLBAR_BUTTON_ID);
            navBar.setAttribute("currentset", set.join(","));
            document.persist("nav-bar", "currentset");
        }

        navBar.insertItem(this.TOOLBAR_BUTTON_ID);
    }
    catch(ex)
    {
        dump("Exception during checkButtonOnToolbar: " + ex + "\n");
    }
}

wwwPrettyTools_GooglePlusOneButtonToollbar.isApiScriptIncluded = function (doc)
{
    try
    {
        var scripts = doc.getElementsByTagName('script');
        for (var i = 0; i < scripts.length; ++i)
        {

            if (!scripts[i].src)
                continue;

            if (scripts[i].src == this.GOOGLE_PLUS_ONE_API_URL)
                return true;
        }
    }
    catch(ex)
    {
        dump("Exception during isApiScriptIncluded: " + ex + "\n");
    }
    return false;
}

wwwPrettyTools_GooglePlusOneButtonToollbar.injectButton = function (doc)
{
    try
    {
        if (doc.getElementById(this.DIV_ID) != null)
            return;

        var isApiScriptIncluded = this.isApiScriptIncluded(doc);
        if (isApiScriptIncluded && this.findPlusOneButton() != null)
            return;

        var div = doc.createElement('div');
        div.id = this.DIV_ID;
        // hide button
        div.style.position = "absolute";
        div.style.filter = "alpha(opacity: 0)";
        div.style.opacity = "0";
        div.style.zIndex = "-1";
        div.style.width = "1px";
        div.style.maxWidth = "1px";
        div.style.height = "1px";
        div.style.maxHeight = "1px";
        div.style.top = "0";
        div.style.left = "0";

        var ifrm = doc.createElement('iframe');
        ifrm.style.width = "1px";
        ifrm.style.maxWidth = "1px";
        ifrm.style.height = "1px";
        ifrm.style.maxHeight = "1px";

        var encodedUrl = encodeURIComponent(doc.location.href);
        var pos = doc.location.href.indexOf("/", 8);
        var encodedParentUrl = pos != -1 ? encodeURIComponent(doc.location.href.substr(0, pos)) : encodedUrl;

        ifrm.src = this.GOOGLE_PLUS_ONE_FRAME_URL.replace("%url%", encodedUrl).replace("%origin%", encodedParentUrl).replace("%parent%", encodedParentUrl);

        div.appendChild(ifrm);
        doc.body.appendChild(div);
    }
    catch(ex)
    {
        dump("Exception during injectButton: " + ex + "\n");
    }
}

wwwPrettyTools_GooglePlusOneButtonToollbar.onPageShow = function (event)
{
    try
    {
        var doc = event.target;

        if (!doc.location.href.match(/^http/))
            return;

        if (this.isPlusOneIFrameUrl(doc.location.href))
        {
            var btn = doc.getElementById("button");
            if (btn) btn.addEventListener("click", function() {
                setTimeout(function(){ wwwPrettyTools_GooglePlusOneButtonToollbar.updateToolbarButton(); }, 500);
                setTimeout(function(){ wwwPrettyTools_GooglePlusOneButtonToollbar.updateToolbarButton(); }, 2000);
            }, false);
        }
        else if ((event.originalTarget instanceof HTMLDocument) && (!event.originalTarget.defaultView.frameElement)) // skip frames
        {
            this.injectButton(doc);
        }

        this.updateToolbarButton();
    }
    catch(ex)
    {
        dump("Exception during onPageShow: " + ex + "\n");
    }
}

wwwPrettyTools_GooglePlusOneButtonToollbar.findChild = function (elem, tag)
{
    try
    {
        if (!elem)
            return null;

        if (elem.tagName == tag)
            return elem;

        for (var i = 0; i < elem.childNodes.length; ++i)
        {
            var ifrm = this.findChild(elem.childNodes[i], tag);
            if (ifrm)
                return ifrm;
        }
    }
    catch(e)
    {
        dump("Exception during findChild: " + e + "\n");
    }
    return null;
}

wwwPrettyTools_GooglePlusOneButtonToollbar.isPlusOneIFrameUrl = function (url)
{
    return url.indexOf(this.GOOGLE_PLUS_ONE_DOMAIN) != -1 && url.indexOf(this.GOOGLE_PLUS_ONE_FRAME_TEST) != -1;
}

wwwPrettyTools_GooglePlusOneButtonToollbar.findPlusOneIFrame = function ()
{
    var frames = window.content.document.getElementsByTagName("IFRAME");
    for (var i = 0; i < frames.length; ++i)
        if (this.isPlusOneIFrameUrl(frames[i].src))
            return frames[i];

    var div = window.content.document.getElementById(this.DIV_ID);

    return !div ? null : this.findChild(div, "IFRAME");
}

wwwPrettyTools_GooglePlusOneButtonToollbar.findPlusOneButton = function ()
{
    try
    {
        var ifrm = this.findPlusOneIFrame();

        if (!ifrm)
            return null;

        var btn = ifrm.contentDocument.getElementById("button");
        if (!btn)
            btn = this.findChild(ifrm.contentDocument.body, "A");

        return btn;
    }
    catch(e)
    {
        dump("Exception during findPlusOneButton: " + e + "\n");
    }
}

wwwPrettyTools_GooglePlusOneButtonToollbar.onPressButton = function ()
{
    try
    {
        var b = this.findPlusOneButton();

        if (b)
        {
            var btn = document.getElementById(this.TOOLBAR_BUTTON_ID);
            var ariaPressed = ("true" == btn.getAttribute("aria-pressed"));
            var pageHasNoButton = window.content.document.getElementById(this.DIV_ID) != null;

            b.click();

            if (wwwPrettyTools_GooglePlusOneButtonConfiguration.isOpenSharePopup() && !ariaPressed && pageHasNoButton)
            {
                var left = (screen.width / 2) - (300);
                var top = (screen.height / 2) - (200);
                var pageURL = encodeURIComponent(window.content.document.location.href);
                var shareUrl = this.GOOGLE_PLUS_SHARE_URL.replace("%url%", pageURL).replace("%url%", pageURL);

                window.open(shareUrl, "_blank", "top="+top+",left="+left+",width=500,height=400,resizable=1");
            }
        }
    }
    catch(e)
    {
        dump("Exception during onPressButton: " + e + "\n");
    }
}

wwwPrettyTools_GooglePlusOneButtonToollbar.disableToolbarButton = function ()
{
    var btn = document.getElementById(this.TOOLBAR_BUTTON_ID);
    if (btn)
    {
        btn.setAttribute("disabled", "true");
        btn.removeAttribute("tooltiptext");
        btn.setAttribute("label", "    ");
        btn.setAttribute("aria-pressed", "false");
    }
}

wwwPrettyTools_GooglePlusOneButtonToollbar.hideToolTipButton = function ()
{
    var txt = document.getElementById(this.TOOLBAR_BUTTON_ID);
    if (txt) txt.setAttribute("label", "    ");
}

wwwPrettyTools_GooglePlusOneButtonToollbar.updateToolbarButton = function ()
{
    try
    {
        var btn = document.getElementById(this.TOOLBAR_BUTTON_ID);
        if (!btn)
            return;

        var b = this.findPlusOneButton();
        if (!b)
            this.disableToolbarButton();
        else
        {
            btn.removeAttribute("disabled");
            var ariaPressedAttribute = b.getAttribute("aria-pressed");
            if (ariaPressedAttribute != null)
                btn.setAttribute("aria-pressed", ariaPressedAttribute);
            else if (b.className)
                btn.setAttribute("aria-pressed", b.className.split(" ").indexOf("jd") != -1);

            var ifrm = this.findPlusOneIFrame();
            if (!ifrm)
            {
                btn.setAttribute("label", "    ");
                btn.setAttribute("tooltiptext", b.title);
            }
            else
            {
                var countDiv = ifrm.contentDocument.getElementById("aggregateCount");
                var label = countDiv ? countDiv.textContent : "";
                while (label.length < 4)
                    label += " ";
                btn.setAttribute("label", label);

                var bubbleDiv = ifrm.contentDocument.getElementById("aggregateBubble");
                if (!bubbleDiv || !bubbleDiv.getAttribute("title"))
                    btn.setAttribute("tooltiptext", b.title);
                else
                    btn.setAttribute("tooltiptext", b.title + "\n" + bubbleDiv.getAttribute("title"));
            }
        }
    }
    catch(e)
    {
        dump("Exception during updateToolbarButton: " + e + "\n");
        this.disableToolbarButton();
    }
}

try
{
    addEventListener("load", function(event) {
        try {
            wwwPrettyTools_GooglePlusOneButtonToollbar.onLoad(event);
        } catch(ex) {
            dump("Exception on inilializing PlusOneButtonToollbar.js: " + ex + "\n");
        }
    }, false);
}
catch(ex)
{
    dump("Exception on inilializing PlusOneButtonToollbar.js: " + ex + "\n");
}
